package logic

import (
	"context"
	"course_srv/course"
	"course_srv/internal/svc"
	"course_srv/models/mysql"
	"course_srv/pkg"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *course.CreateOrderRequest) (*course.CreateOrderResponse, error) {
	c := mysql.Course{}
	err := c.CourseShow(int(in.CourseId))
	if err != nil {
		return nil, errors.New("查询失败")
	}
	if c.ID == 0 {
		return nil, errors.New("课程不存在")
	}

	err = c.GetCourseStatusId()
	if err != nil {
		return nil, errors.New("查询失败")
	}
	if c.StatusId != 1 {
		return nil, errors.New("课程未上架")
	}
	orderSn := uuid.NewString()
	price := c.Price
	o := mysql.Order{
		UserId:  int(in.UserId),
		OrderSn: orderSn,
		Amount:  price,
	}
	err = o.Add()
	if err != nil {
		return nil, errors.New("订单创建失败")
	}
	oc := mysql.OrderCourse{
		CourseId: int(in.CourseId),
		OrderId:  int(o.ID),
		Name:     c.Name,
		Intro:    c.Intro,
	}
	err = oc.Add()
	if err != nil {
		return nil, errors.New("订单课程创建失败")
	}
	p := fmt.Sprintf("%.2f", price)
	if o.PayType == 1 {
		fmt.Println("支付宝支付")
		url := pkg.AliPay(orderSn, p)
		return &course.CreateOrderResponse{OrderId: int32(o.ID), PayUrl: url}, nil
	}
	if o.PayType == 2 {
		fmt.Println("微信支付")
	}

	return &course.CreateOrderResponse{OrderId: int32(o.ID)}, nil
}
